<?php

namespace backend\controllers;

use bc\api\SzApi;
use bc\controller\BackendController;
use bc\model\BindModel;
use bc\model\DictCityModel;
use bc\model\DictProvinceModel;
use bc\model\ExpressModel;
use bc\model\ItemModel;
use bc\model\OrderbindMode;
use bc\model\OrderModel;
use bc\model\ProductModel;
use bc\model\UserreportModel;
use bc\model\wc\SpreadModel;
use bc\util\Util;
use yii;
use bc\util\backend\Page;
use yii\web\Session;

class SampleController extends BackendController
{
    private static $samplestatus = array('1'=>'采样盒未寄出','2'=>'采样盒寄出','3'=>'样本已绑定','4'=>'检查中','5'=>'待处理','6'=>'已出报告');
    public function actionIndex()
    {
        $model = new BindModel();
        $page = $this->get('page', 1);
        $params='';
        //$params=array('bc_item_data.item_product_id'=>1);

		$order_no = $this->get('order_no', '');
		$bind_no = $this->get('bind_no', '');
        $smaple_status = $this->get('smaple_status', '');
        $tracking_no = $this->get('tracking_no','');
        $product_id = $this->get('product_id',2);

        //订单号
		if($order_no != ''){
			$params='bc_order.order_no like "%'. $order_no . '%" ' ;
		}

        //样本
		if($bind_no != ''){
            if(!empty($params)){
                $arrStr = explode($params, 'and');
                if (!$arrStr[count($arrStr)-1] == "") {
                    $params.=' and ';
                }
            }

            $params.='bc_order_bind.bind_no like "%'. $bind_no . '%"' ;
		}

        //样本状态
        if($smaple_status != '' && $smaple_status!=0 ){
            if(!empty($params)){
                $arrStr = explode($params, 'and');
                if (!$arrStr[count($arrStr)-1] == "") {
                    $params.=' and ';
                }
            }

            $params.='bc_order_bind.bind_status ='. $smaple_status ;
        }

        //样本状态
        if($tracking_no != ''){
            if(!empty($params)){
                $arrStr = explode($params, 'and');
                if (!$arrStr[count($arrStr)-1] == "") {
                    $params.=' and ';
                }
            }

            $params.='bc_express.tracking_no like "%'. $tracking_no .'%" ' ;
        }

        //样本产品
        if($product_id != ''){
            if(!empty($params)){
                $arrStr = explode($params, 'and');
                if (!$arrStr[count($arrStr)-1] == "") {
                    $params.=' and ';
                }
            }
            $params.='bc_order_bind.product_id ='. $product_id ;
        }
        $model->sort='bc_order.create_time desc';
        $list = $model -> getReportList($params, $page, self::PAGE_SIZE);
        //给数据添加序号
//        $tempid=-1;
//        foreach($list as $k => $v){
//            if($v['order_id'] != $tempid){
//                $tempid=$v['order_id'];
//                $size=1;
//            }
//            $list[$k]['size']=$size++;
//        }

        $total = $model->getTotal($params);

        $pagination = new Page($total, self::PAGE_SIZE);

        //echo "<pre>";
        //var_dump($list);die();
		$view['order_no'] = $order_no;
		$view['bind_no'] = $bind_no;
        $view['list'] = $list;
        $view['pagination'] = $pagination;
        $view['samplestatus'] = self::$samplestatus;
        $view['smaple_status'] = $smaple_status;
        $view['tracking_no'] = $tracking_no;
        return $this->render('index',$view);
    }

    //ajax
    public function  actionAjaxlrno()
    {
        $bind_id = $this->get("bind_id");
        $bind_no = $this->get("bind_no");

        //获取产品id
        $orderbindM = new OrderbindMode();
        $orderbindM->autoId='bind_id';
        if(!empty($orderbindM->getRowP(['bind_no'=>$bind_no])))
        {
            $data = array(
                'error' => '1',
                'msg' => '绑定号已使用，请检查是否输入正确！'
            );
            echo json_encode($data);
            die();
        }else{
            //检测订单是否已经取消，取消的订单不能绑定样本号
            $orderbindD=$orderbindM->getRowById($bind_id);
            if(empty($orderbindD)){
                $data = array(
                    'error' => '1',
                    'msg' => '请查看是否输入正确！'
                );
                echo json_encode($data);
                die();
            }

            $orderModel = new OrderModel();
            $orderModel->autoId='order_id';
            $orderD=$orderModel->getRowById($orderbindD['order_id']);
            if(empty($orderD)){
                $data = array(
                    'error' => '1',
                    'msg' => '请查看是否输入正确！'
                );
                echo json_encode($data);
                die();
            }elseif($orderD['order_status'] == 5){
                $data = array(
                    'error' => '1',
                    'msg' => '订单已取消！'
                );
                echo json_encode($data);
                die();
            }
        }
        $orderbindM->autoId='bind_id';
        $orderbindD = $orderbindM->getRowById($bind_id);
       // var_dump($orderbindD);die();
        if($orderbindD['product_id'] == 2) {
            //验证采样管编号
            $szapi = new SzApi();
            $szapiData = json_decode($szapi->searchInfo($bind_no), true);
            if ($szapiData['retCode'] !== 0) {
                $data = array(
                    'error' => '1',
                    'msg' => '验证失败，请检查录入编号！'
                );
                echo json_encode($data);
                die();
            }
        }
		$session = new Session ();
		$shop_user = $session->get ( 'admin' );
		$account = $shop_user ['account'];

        $model = new BindModel();
        if ($bind_no || $bind_id) {
            $model->modify(array(
            	'bind_no' => $bind_no,
				'bind_status' => 2,
				'create_time' => time(),
			), $bind_id);

            $info = $model->getRow(['bind_id'=>$bind_id]);
			$orderModel = new OrderModel();
			$orderModel->modify([
                'order_status'	=>	3,
				'send_time'	=>	time(),
				'send_user'	=>	$account,
			], $info['order_id']);
        }

        $model->autoId = 'bind_id';
        $bindInfo = $model->getOrderInfoByBindid($bind_id);
        echo json_encode($bindInfo);
    }

    public function actionSampleinfo()
    {
        $bind_id=$this->get("bind_id");
        $size = $this->get('size');
		$model = new BindModel();
        $view['sampleinfo'] = $model->getSampleInfo($bind_id);
		$view['size'] = $size;
        //根据bind_no获取产品id
        $OrderbindM= new OrderbindMode();
//        $OrderbindM->columns='bc_order_bind.user_id as ouser_id,bc_order_bind.product_id as oproduct_id,bc_order_bind.bind_no as obind_no';
        $OrderbindM->autoId='bind_id';
        $OrderbindD=$OrderbindM->getRowById($bind_id);
        $bind_no=$OrderbindD['bind_no'];
        $user_id=$OrderbindD['user_id'];
        $product_id = $OrderbindD['product_id'];
        $ItemM = new ItemModel();
        $ItemD = $ItemM->getUserInfoByUseridAndProductId($user_id,$product_id,$bind_no);
        foreach($ItemD as $k => $value){
            if($value['biitem_type']==2 || $value['biitem_type']==3 ){
                if(empty($data[$value['report_key']])){
                    if($value['bsitem_type'] == 1) {
                        $data[$value['report_key']] = $value['subitem_value'];
                    }else{
                        $data[$value['report_key']] = $value['subitem_name'];
                    }
                }else {
                    if($value['bsitem_type'] == 1){
                        $data[$value['report_key']] = $data[$value['report_key']] . ";" . $value['subitem_value'];
                    }else{
                        $data[$value['report_key']] = $data[$value['report_key']] . ";" . $value['subitem_name'];
                    }

                }

            }elseif($value['biitem_type']==4){
                $adderssStr='';
                $adderss = explode(',',$value['item_value']);
                $DictProvinceM = new DictProvinceModel();
                $DictCityM = new DictCityModel();
                if(isset($adderss[0])){
                    $DictProvinceM->columns='province_name';
                    $adderssStr = $DictProvinceM->getRowById($adderss[0])['province_name'];
                }
                if(isset($adderss[1])){
                    $DictCityM->columns='city_name';
                    $adderssStr .=$DictCityM->getRowById($adderss[1])['city_name'];
                }

                $data['adderssStr']=$adderssStr;
            }else{
                $data[$value['report_key']]=$value['item_value'];
            }
        }
        //判断产品为2时
        if($product_id ==2 && isset($data['info_height']) ) {
            //计算BMI=体重/身高*身高
            if ($data['info_height'] == 0 || $data['info_weight'] == 0) {
                $data['info_bmi'] = "数值错误";
            } else {
                $data['info_bmi'] = round($data['info_weight'] / (($data['info_height'] / 100) * ($data['info_height'] / 100)), 1);
            }
        }

        $view['Data'] = isset($data)?$data : array();

        //获取样本快递信息
        $expressM = new ExpressModel();
        $expressD = $expressM->getSendinfo(['bc_express.bind_id'=>$bind_id]);
        $view['expressD']=isset($expressD[0])? $expressD[0] : array();

        $UserreportM = new UserreportModel();
        $UserreportData = $UserreportM->getInfoFromBindno($product_id,$bind_no);
        $view['reportinfo'] = $UserreportData;
        $view['product_id'] = $product_id;
        $view['bind_no'] = $bind_no;
        $view['user_id'] = $user_id;
        $view['bind_id'] = $bind_id;
        return $this->render('sampleinfo',$view);
    }

    //编辑报告综合解读
    public function actionEditreport()
    {
        $bind_id=$this->get("bind_id");
        if(empty($bind_id)) {
            echo "错误，请重试！";
            die();
        }

        //获取绑定信息
        $orderbindM = new OrderbindMode();
        $orderbindM->autoId='bind_id';
        $orderbindD=$orderbindM->getRowById($bind_id);

        //获取样本信息
        $UserreportM = new UserreportModel();
        $UserreportData = $UserreportM->getInfoFromBindno($orderbindD['product_id'],$orderbindD['bind_no']);
        $view['reportinfo'] = $UserreportData;
        $view['product_id'] = $orderbindD['product_id'];
        $view['bind_no'] = $orderbindD['bind_no'];
        $view['user_id'] = $orderbindD['user_id'];
        $view['bind_id'] = $orderbindD['bind_id'];
        return $this->render('editreport',$view);
    }

    //保存数据
    public function actionSave()
    {
        $product_id =$this->post('product_id');
        $bind_no =$this->post('bind_no');
        $user_id =$this->post('user_id');
        $bind_id =$this->post('bind_id');
        $report_mixed_summary =$this->post('report_mixed_summary');
        if(empty($product_id) || empty($bind_no))
        {
            echo "错误，请重新编辑！";
            die();
        }

        $where = array(
            'product_id' => $product_id,
            'bind_no' => $bind_no,
            'report_key' => 'report_mixed_summary'
        );

        $userreportM = new UserreportModel();
        $userreportM->deleteAll($where);

        $report_interData=array(
            'product_id' => $product_id,
            'bind_no' => $bind_no,
            'user_id' => $user_id,
            'report_key' => 'report_mixed_summary',
            'report_value' => $report_mixed_summary
        );
        $returnid = $userreportM->add($report_interData);

        //修改样本状态
        $orderbindM = new OrderbindMode();
        $orderbindM->autoId='bind_id';
        $orderbindM->modify(['bind_status'=>6],$bind_id);

        $output['msg'] = '保存成功';
        $output['url'] = '/sample/sampleinfo?bind_id='.$bind_id ;
        $this->forward($output);
        //$this->redirect ( '/sample/editreport?bind_id='.$bind_id );

    }
}
